/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

var sendChatReq = getXmlHttpRequestObject();
var receiveChatReq = getXmlHttpRequestObject();

function writeChatBox(message, type, name) {
    var containerId = "chatbox_"+type+"_"+name;
    if ($(containerId)==null) {
        newChat(type, name);
    }
    $(containerId).getElementsByTagName("div")[0].innerHTML += message + "<br/>";
    $(containerId).getElementsByTagName("div")[0].scrollTop = $(containerId).scrollHeight*65536;
}

function chatInputHandler(e, object) {
    var key = e.keyCode || e.which;
    if (key == 13 && object.value.ltrim() != "") {
        var type = object.parentNode.getElementsByTagName("input")[1].value;
        var name = object.parentNode.getElementsByTagName("input")[2].value;
        parseCommand(object.value.ltrim(),type,name);
        object.value = "";
    }
}

function parseCommand(input, type, name) {
    // parsing comman atau bukan
    if (input.toString().charAt(0) == '/') {
        // command
        commandSplit = input.split(" ");
        command = commandSplit[0];

        if (commandSplit.length == 1 && (
            command == "/exit" ||
            command == "/info")) {
            callCommand(command,"","",type,name);
        }
        else if (commandSplit.length == 2 && (
            command == "/create" ||
            command == "/join" ||
            command == "/chat" ||
            command == "/addfriend" ||
            command == "/info" ||
            command == "/kick" ||
            command == "/ban" ||
            command == "/unban" ||
            command == "/persist" ||
            command == "/setowner")) {
            callCommand(command,commandSplit[1],"",type,name);
            /*
            if (command == "/chat") {
                if ($("chattab_user_"+commandSplit[1]) == null) {
                    newChat("user", commandSplit[1]);
                }
            }
            */
        }
        else if (commandSplit.length == 3 && (
            command == "/create")) {
            callCommand(command,commandSplit[1],commandSplit[2],type,name);
        }
        else {
            writeChatBox("Command salah"+"<br/>",type,name);
        }
    }
    else {
        // bukan command
        callChatSender(input,type,name);
    }
}

function callCommand(command, param1, param2, type, name) {
    //writeChatBox("Memanggil command "+command+"->"+param1+" "+param2+"<br/>",type,name);
    // pake ajax disini buat manggil command
    sendChatReq.open("GET","ajax/command?command="+command+"&param1="+param1+"&param2="+param2+"&type="+type+"&name="+name,true);
    sendChatReq.send();

    sendChatReq.onreadystatechange=function()
    {
        if (sendChatReq.readyState==4 && sendChatReq.status==200)
        {
            //alert("tulis sendiri = "+sendChatReq.responseText);
            var xmlResponse = sendChatReq.responseXML;
            if (xmlResponse != null) {
                parseCommandXML(xmlResponse);
            }
        }
    }
}

function callChatSender(message, type, name) {
    //writeChatBox(message+"<br/>",type,name);
    // pake ajax disini buat posting chat
    sendChatReq.open("GET","ajax/chat?message="+message+"&type="+type+"&name="+name,true);
    sendChatReq.send();

    sendChatReq.onreadystatechange=function()
    {
        if (sendChatReq.readyState==4 && sendChatReq.status==200)
        {
            //alert("tulis sendiri = "+sendChatReq.responseText);
            var xmlResponse = sendChatReq.responseXML;
            if (xmlResponse != null) {
                parseXML(xmlResponse);
            }
        }
    }
}

function receiveChat() {
    // fungsi untuk menerima message via ajax
    receiveChatReq.open("GET","ajax/receive",true);
    receiveChatReq.send();

    receiveChatReq.onreadystatechange=function()
    {
        if (receiveChatReq.readyState==4 && receiveChatReq.status==200)
        {
            //alert("pesan orang = "+receiveChatReq.responseText);
            var xmlResponse = receiveChatReq.responseXML;
            if (xmlResponse != null) {
                parseXML(xmlResponse);
            }
            setTimeout('receiveChat();',1000);
        }
    }
}

function newChat(type, name) {
    if ($("chattab_"+type+"_"+name)!=null) {
        // nothing
    }
    else {
        // membuat tab
        var newTab = document.createElement("div");
        newTab.setAttribute("class", "chattab_inactive");
        newTab.setAttribute("id", "chattab_"+type+"_"+name);
        $("chattab_container").appendChild(newTab);

        var newTabName = document.createElement("span");
        newTabName.setAttribute("class", "chat_name");
        newTabName.setAttribute("onclick", "showChat(this.parentNode)");
        if (type == "room") {
            newTabName.innerHTML = "#";
        }
        else {
            newTabName.innerHTML = "";
        }
        newTabName.innerHTML += name;
        newTab.appendChild(newTabName);

        var newTabClose = document.createElement("span");
        newTabClose.setAttribute("class", "chat_close");
        newTabClose.setAttribute("onclick", "closeChat(this.parentNode)");
        newTabClose.innerHTML = "<img class=\"close\" src=\"images/wrong.png\" />";
        newTab.appendChild(newTabClose);

        var newTabInput1 = document.createElement("input");
        newTabInput1.setAttribute("type", "hidden");
        newTabInput1.setAttribute("name", "type");
        newTabInput1.setAttribute("value", type);
        newTab.appendChild(newTabInput1);

        var newTabInput2 = document.createElement("input");
        newTabInput2.setAttribute("type", "hidden");
        newTabInput2.setAttribute("name", "name");
        newTabInput2.setAttribute("value", name);
        newTab.appendChild(newTabInput2);

        // membuat chatbox
        var newBox = document.createElement("div");
        newBox.setAttribute("class", "chatbox_inactive");
        newBox.setAttribute("id", "chatbox_"+type+"_"+name);
        $("chatbox_container").appendChild(newBox);

        var newBoxMessage = document.createElement('div');
        newBoxMessage.setAttribute("class", "chat_message");
        newBox.appendChild(newBoxMessage);

        var newBoxInput = document.createElement('div');
        newBoxInput.setAttribute("class", "chat_input");
        newBox.appendChild(newBoxInput);

        var newBoxInput0 = document.createElement("input");
        newBoxInput0.setAttribute("type", "text");
        newBoxInput0.setAttribute("onkeypress", "chatInputHandler(event,this)");
        newBoxInput.appendChild(newBoxInput0);

        var newBoxInput1 = document.createElement("input");
        newBoxInput1.setAttribute("type", "hidden");
        newBoxInput1.setAttribute("name", "type");
        newBoxInput1.setAttribute("value", type);
        newBoxInput.appendChild(newBoxInput1);

        var newBoxInput2 = document.createElement("input");
        newBoxInput2.setAttribute("type", "hidden");
        newBoxInput2.setAttribute("name", "name");
        newBoxInput2.setAttribute("value", name);
        newBoxInput.appendChild(newBoxInput2);
    }
}

function inactivate() {
    var activeChat = document.getElementsByClassName("chattab_active");
    if (activeChat[0]!=null) {
        activeChat[0].setAttribute("class", "chattab_inactive");
    }
    activeChat = document.getElementsByClassName("chatbox_active");
    if (activeChat[0]!=null) {
        activeChat[0].setAttribute("class", "chatbox_inactive");
    }
}

function showChat(object) {
    inactivate();
    var type = object.getElementsByTagName("input")[0].value;
    var name = object.getElementsByTagName("input")[1].value;
    object.setAttribute("class", "chattab_active");
    $("chatbox_"+type+"_"+name).setAttribute("class", "chatbox_active");
    $("chatbox_"+type+"_"+name).getElementsByTagName("input")[0].focus();
}

function closeChat(object) {
    var type = object.getElementsByTagName("input")[0].value;
    var name = object.getElementsByTagName("input")[1].value;
    if ($("chattab_"+type+"_"+name).className == "chattab_active") {
        $("chattab_room_home").setAttribute("class", "chattab_active");
        $("chatbox_room_home").setAttribute("class", "chatbox_active");
    }
    $("chattab_container").removeChild(object);
    $("chatbox_container").removeChild($("chatbox_"+type+"_"+name));
}

function parseXML(xmlObject) {
    var listMessage;
    var type;
    var name;
    var content;

    listMessage = xmlObject.getElementsByTagName("message");
    for (i=0;i<listMessage.length;i++){
        type = listMessage[i].getElementsByTagName("type")[0].childNodes[0].nodeValue;
        name = listMessage[i].getElementsByTagName("name")[0].childNodes[0].nodeValue;
        content = listMessage[i].getElementsByTagName("content")[0].childNodes[0].nodeValue;
        writeChatBox(content, type, name);
    }
}

function parseCommandXML(xmlObject) {
    var command;
    var type;
    var name;
    var content;

    if (xmlObject.getElementsByTagName("status")[0].childNodes[0].nodeValue == 1) {
        command = xmlObject.getElementsByTagName("command")[0].childNodes[0].nodeValue;
        type = xmlObject.getElementsByTagName("type")[0].childNodes[0].nodeValue;
        name = xmlObject.getElementsByTagName("name")[0].childNodes[0].nodeValue;
        content = xmlObject.getElementsByTagName("content")[0].childNodes[0].nodeValue;

        if (command == "/exit") {
            closeChat($("chattab_"+type+"_"+name));
        }
        else if (command == "/info") {
            alert(content);
        }
        else if (command == "/create") {
            writeChatBox("Welcome to the Room!", type, name);
            showChat($("chattab_"+type+"_"+name));
        }
        else if (command == "/join") {
            if (content == "fail") {
                alert("Room not found!");
            }
            else {
                newChat(type, name);
                showChat($("chattab_"+type+"_"+name));
            }
        }
        else if (command == "/chat") {
            if (content == "fail") {
                alert("User not found!");
            }
            else {
                newChat(type, name);
                showChat($("chattab_"+type+"_"+name));
            }
        }
        else if (command == "/addfriend") {
            alert(content);
        }
        else if (command == "/kick") {
            //alert(content);
        }
        else if (command == "/ban") {
            alert(content);
        }
        else if (command == "/unban") {
            alert(content);
        }
        else if (command == "/persist") {
            alert(content);
        }
        else if (command == "/setowner") {
            alert(content);
        }
    }
    else {
        alert("Execute command failed!!!");
    }
}

function chatClick(name) {
    newChat("user", name);
    showChat($("chattab_user_"+name));
}

function joinClick(name) {
    callCommand("/join", name, "", "", "");
}
